<!-- 新增和编辑弹窗 -->
<template>
  <a-modal
    :width="1000"
    :visible="visible"
    :confirm-loading="loading"
    :title="isUpdate ? '修改产品信息' : '新建产品信息'"
    :body-style="{ paddingBottom: '8px' }"
    @update:visible="updateVisible"
    @ok="save"
  >
    <a-form
      layout="vertical"
      ref="form"
      :model="form"
      :rules="rules"
      :label-col="{ md: { span: 20 }, sm: { span: 24 } }"
      :wrapper-col="{ md: { span: 20 }, sm: { span: 24 } }"
    >
      <a-card :bordered="false">
        <a-row>
          <a-col :span="8">
            <a-form-item label="产品名称:" name="name">
              <a-input v-model:value="form.name" placeholder="请输入产品名称最多20个字符" maxLength="20" allow-clear autocomplete="off" />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="产品编码:" name="code">
              <a-input v-model:value="form.code" placeholder="请输入产品编码最多20个字符" maxLength="20" allow-clear autocomplete="off" />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="产品分类:" name="productTypeId">
              <a-select placeholder="请选择产品分类" v-model:value="form.productTypeId" show-search allow-clear
                        @dropdownVisibleChange="getProductType">
                <a-select-option v-for="item in productTypeList" :key="item.id" :value="item.id">
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
<!--          <a-col :span="8">
            <a-form-item label="库存(BMSH后台参考用):" name="stock">
              <a-input-number v-model:value="form.stock" placeholder="请输入库存" @input="changeInput('stock', 0)"
                              autocomplete="off"
                              :min="0"
                              :max="990000"
                              style="width: 230px"
                              suffix="件" />
              件
            </a-form-item>
          </a-col>-->
<!--          <a-col :span="8">
            <a-form-item label="常规售价:" name="price">
              <a-input-number v-model:value="form.price" placeholder="请输入产品售价" @input="changeInput('price', 2)"
                              autocomplete="off"
                              :min="0"
                              :max="990000"
                              style="width: 230px"
                              suffix="元" />
              元
            </a-form-item>
          </a-col>-->
          <a-col :span="8">
            <a-form-item label="产品排序:" name="dataSort">
              <a-input v-model:value="form.dataSort" placeholder="请输入产品排序" maxlength="2" @input="changeInput('dataSort', 0)"
                       autocomplete="off" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="形象图:" name="imageDetailFileId">
              <a-upload
                accept="image/png,image/jpeg"
                :headers="headers"
                action="/api/sysFileInfo/upload?secretFlag=N"
                list-type="picture-card"
                v-model:file-list="fileList"
                @preview="handlePreview">
                <div v-if="fileList.length < 1">
                  <slot name="icon">
                    <PlusOutlined class="ele-image-upload-icon" />
                  </slot>
                </div>
              </a-upload>
              <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
                <img alt="example" style="width: 100%" :src="previewImage" />
              </a-modal>
            </a-form-item>
          </a-col>
<!--          <a-col :span="12">
            <a-form-item label="使用手册:" name="manualFileId">
              <a-upload
                :headers="headers"
                action="/api/sysFileInfo/upload?secretFlag=N"
                list-type="picture-card"
                v-model:file-list="fileList_sc"
                @preview="handlePreviewPdf">
                <div v-if="fileList_sc.length < 1">
                  <slot name="icon">
                    <PlusOutlined class="ele-image-upload-icon" />
                  </slot>
                </div>
              </a-upload>
&lt;!&ndash;              <a-modal :visible="previewVisiblePdf" :footer="null" @cancel="handleCancelPdf">
                <pdf alt="example" style="width: 100%" :src="previewPdf" />
              </a-modal>&ndash;&gt;
            </a-form-item>
          </a-col>-->
<!--          <a-col :span="24">
            <a-form-item label="产品介绍:" name="introduce" :labelCol="{ span: 20 }" :wrapperCol="{ span: 24 }">
              <tinymce v-model="form.introduce" :disabled='false' :init="{height:500}"></tinymce>
            </a-form-item>
          </a-col>-->
        </a-row>
      </a-card>
    </a-form>
  </a-modal>
</template>

<script>
import { ProductInfoApi } from '@/api/ProductInfoApi';
import { onMounted, ref } from 'vue';
import { ProductTypeApi } from '@/api/ProductTypeApi';
import setting from '@/config/setting';
import tinymce from 'tinymce/tinymce';

export default {
  name: 'PositionEdit',
  components: {},
  emits: ['done', 'update:visible'],
  props: {
    // 弹窗是否打开
    visible: Boolean,
    // 修改回显的数据
    data: Object
  },
  setup() {
    // 加载下拉数据
    const productTypeList = ref([]);
    onMounted(async () => {
      const res = await ProductTypeApi.findList();
      productTypeList.value = res.data;
    });

    const beforeUpload = () => {
      //console.log(info);
      /*if (file.filelist.length >= 1) {
        message.error('请上传正确的迁移文件!(只允许上传json文件)');
        return false;
      }*/
      /*if (file.type !== 'application/json') {
        message.error('请上传正确的迁移文件!(只允许上传json文件)');
        data.fileList = [];
        data.file = null;
        return true;
      }
      data.fileList[0] = file;
      data.file = file;
      return false;*/
      return true;
    };
    /*const handleChange = (info) => {
      // 获取当前上传文件列表
      const currentFileList = info.fileList;
      // 判断文件数量
      const fileCount = currentFileList.length;
      // 如果需要限制数量，可以在这里进行判断和处理
      if (fileCount > 1) {
        // 清除多余的文件，只保留允许的最大数量
        fileList_sc.value = currentFileList.slice(-1);
        // 或者拒绝上传多余的文件，需返回false阻止默认上传行为
        return false;
      }
      // 更新fileList_sc
      fileList_sc.value = currentFileList;
    };*/
    return {
      productTypeList,
      beforeUpload
    };
  },
  data() {
    let numberRule = async (rule, value) => {
      if (!value) {
        if (rule.field === 'price') {
          return Promise.reject('请输入售价');
        } else if (rule.field === 'stock') {
          return Promise.reject('请输入库存');
        } else if (rule.field === 'dataSort') {
          return Promise.reject('请输入排序');
        }
        return Promise.reject('请输入必填信息');
      }
    };

    let picRule = async (rule, value) => {
      if (!value) {
        if (this.fileList.length === 0) {
          return Promise.reject('请上传形象图');
        }
      }
    };


    return {
      // 表单数据
      form: Object.assign({}, this.data),
      // 表单验证规则
      rules: {
        name: [{ required: true, message: '请输入产品名称', type: 'string', trigger: 'blur' }],
        code: [{ required: true, message: '请输入产品编码', type: 'string', trigger: 'blur' }],
        productTypeId: [{ required: true, message: '请选择产品分类', trigger: 'blur' }],
        imageDetailFileId: [{ required: true,validator: picRule, message: '请上传形象图', trigger: 'change' }],
        /*manualFileId: [{ required: true, message: '请上传使用手册', trigger: 'blur' }],*/
        price: [{ required: true, validator: numberRule, trigger: 'blur' }],
        stock: [{ required: true, validator: numberRule, trigger: 'blur' }],
        dataSort: [{ required: true, validator: numberRule, trigger: 'blur' }],
        introduce: [{ required: true, message: '请输入产品介绍', type: 'string', trigger: 'blur' }]
      },
      // 提交状态
      loading: false,
      // 是否是修改
      isUpdate: false,
      // 角色列表
      roleList: [],
      // 组织机构树列表
      orgList: [],
      // 职位列表
      positionList: [],
      // 上传图片时候的header
      headers: {
        Authorization: setting.takeToken()
      },
      // 是否可以预览
      previewVisible: false,
      // 预览图片的地址
      previewImage: '',

      previewVisiblePdf: false,
      previewPdf: '',
      // 上传文件列表
      fileList: [],
    };
  },
  watch: {
    async data() {
      if (this.data) {
        console.log("编辑清空")
        const resData = await ProductInfoApi.detail({ id: this.data.id });
        this.form = Object.assign({}, resData.data);

        //文件列表赋值
        this.isUpdate = true;
        // 拼接文件预览的url
        let token = setting.takeToken();
        if (this.form.imageDetailFileId) {
          this.fileList = [{
            name: '',
            url: `/api/sysFileInfo/public/preview?fileId=${this.form.imageDetailFileId}&token=${token}`
          }];
        }
        if (this.form.manualFileId) {
          this.fileList_sc = [{
            name: '',
            thumbUrl: `https://img0.baidu.com/it/u=3676194743,3100501382&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500`,
            url: `/api/sysFileInfo/publicDownload?fileId=${this.form.manualFileId}&token=${token}`
          }];
        }
      } else {
        this.isUpdate = false;
      }
      if (this.$refs.form) {
        this.$refs.form.clearValidate();
      }
    },
    async visible(){
      // 清空表单校验信息
      if (this.$refs.form) {
        this.$refs.form.clearValidate();
      }
      if (!this.data) {
        // 新增-清除表格内容
        this.form = {};
        // 新增-清除富文本框内容
        if (tinymce.get('introduce')) {
          tinymce.get('introduce').setContent('');
        }
        // 新增-文件列表内容
        this.fileList = [];
        this.fileList_sc = [];
      } else {
        this.form = Object.assign({}, this.data);
      }
    }
  },
  methods: {

    async getProductType() {
      const res = await ProductTypeApi.findList();
      this.productTypeList = res.data;
    },

    /**
     * 保存和编辑职务
     */
    async save() {
      // 校验表单
      await this.$refs.form.validate();

      // 设置公司图片的id
      if (this.fileList.length > 0) {
        if (this.fileList[0]?.response) {
          this.form.imageDetailFileId = this.fileList[0].response.data.fileId;
        }
      } else {
        this.form.imageDetailFileId = null;
        this.$message.error('请上传形象图');
        return;
      }

      /*if (this.fileList_sc.length > 0) {
        if (this.fileList_sc[0]?.response) {
          this.form.manualFileId = this.fileList_sc[0].response.data.fileId;
        }
      } else {
        this.form.manualFileId = null;
        this.$message.error('请上传使用手册');
        return;
      }*/

      // 修改加载框为正在加载
      this.loading = true;

      let result = null;

      // 执行编辑或修改
      if (this.isUpdate) {
        result = ProductInfoApi.edit(this.form);
      } else {
        result = ProductInfoApi.add(this.form);
      }
      result
        .then(result => {
          // 移除加载框
          this.loading = false;

          // 提示添加成功
          this.$message.success(result.message);

          // 如果是新增，则form表单置空
          if (!this.isUpdate) {
            this.form = {};
          }

          // 关闭弹框，通过控制visible的值，传递给父组件
          this.updateVisible(false);

          // 触发父组件done事件
          this.$emit('done');
        })
        .catch(() => {
          this.loading = false;
        });
    },
    /**
     * 更新编辑界面的弹框是否显示
     *
     * @param value true-显示，false-隐藏
     * @author fengshuonan
     * @date 2021/4/7 11:00
     */
    updateVisible(value) {
      this.$emit('update:visible', value);
    },
    changeInput(key, scale) {
      const val = this.form[key];
      //判断是否是数字类型
      if (isNaN(val)) {
        this.form[key] = Number(val.slice(0, val.length - 1));
      } else {
        //判断是否是小数
        if (val.indexOf('.') !== -1) {
          //判断小数点后面的位数
          if (val.split('.')[1].length > scale) {
            this.form[key] = Number(val.slice(0, val.length - 1));
          }
        }
      }
    },
    /**
     * 点击预览图片时
     */
    handlePreview(file) {
      // 打开预览框
      this.previewVisible = true;
      // 获取到文件id
      let fileId = file?.response?.data?.fileId;
      if (!fileId) {
        // 拼接文件预览的url
        this.previewImage = file.url;
      } else {
        // 拼接文件预览的url
        let token = setting.takeToken();
        this.previewImage = `/api/sysFileInfo/public/preview?fileId=${fileId}&token=${token}`;
      }
    },

    /**
     * 点击取消按钮
     */
    handleCancel() {
      this.previewVisible = false;
    },

    /**
     * 点击预览使用手册
     */
    handlePreviewPdf(file) {

      // 获取到文件id
      let fileId = file?.response?.data?.fileId;
      if (!fileId) {
        // 拼接文件预览的url
        this.previewPdf = file.url;
        // 新窗口打开url
        window.open(this.previewPdf);
      } else {
        // 拼接文件预览的url
        let token = setting.takeToken();
        this.previewPdf = `/api/sysFileInfo/public/preview?fileId=${fileId}&token=${token}`;
        // 新窗口打开url
        window.open(this.previewPdf);
      }
    },
    /**
     * 点击取消按钮
     */
    handleCancelPdf() {
      this.previewVisiblePdf = false;
    },



  }
};
</script>

<style scoped>
</style>

<style scoped>
/*.ele-image-upload-icon {
  font-size: 22px;
  color: @text-color-secondary;
  opacity: 0.8;
}*/
</style>
